package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.EasyExcelImportUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.model.entity.SysDict;
import com.settlement.system.model.entity.SysDictType;
import com.settlement.system.service.SysDictService;
import com.settlement.system.service.SysDictTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * <p>
 * 平台字段导入前端控制器
 * </p>
 *
 * @author huangrensen
 */
@Tag(name = "平台单据字段导入控制器")
@RestController
@RequestMapping("/api/v1/columnImport")
@RequiredArgsConstructor
public class PlatFormColumnImportController {

    private final SysDictService sysDictService;

    private final SysDictTypeService sysDictTypeService;

    @Operation(summary = "保存平台单据字段", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("save/{platformKey}/{type}")
    @PreAuthorize("@ss.hasPerm('sys:columnImport:save')")
    @PreventDuplicateSubmit
    public Result<?> save(@Parameter(description = "平台KEY") @PathVariable String platformKey, @Parameter(description
            = "单据类型（订单order、账单bill）") @PathVariable String type, @RequestParam("file") MultipartFile file) {
        // 先将excel表格的表头读取出来
        Map<Integer, String> firstMap = EasyExcelImportUtils.makeHeader(file);
        // 将历史的关于此平台的配置删除，重新保存
        List<SysDictType> sysDictTypes =
                sysDictTypeService.list(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getCode, platformKey + type));
        if (sysDictTypes.size() == 0) {
            // 需要新建一种字段配置
            List<Option> optionList = sysDictService.listDictOptions("platform");
            optionList.stream().filter(option -> option.getValue().equals(platformKey))
                    .findFirst()
                    .ifPresent(option -> {
                        SysDictType sysDictType = new SysDictType();
                        sysDictType.setStatus(1);
                        sysDictType.setCode(platformKey + type);
                        if ("order".equals(type)) {
                            sysDictType.setName(option.getLabel() + "订单");
                            sysDictType.setRemark("%s平台订单字段配置".formatted(option.getLabel()));
                        } else {
                            sysDictType.setName(option.getLabel() + "账单");
                            sysDictType.setRemark("%s平台账单字段配置".formatted(option.getLabel()));
                        }
                        sysDictTypeService.save(sysDictType);
                    });
        }
        // 删除原来字段配置
        sysDictService.deleteAllByTypeCode(platformKey + type);
        List<String> columns = firstMap.values().stream().toList();
        List<SysDict> sysDictList = new ArrayList<>();
        // 索引
        int index = 1;
        //  循环字段名称
        for (String column : columns) {
            SysDict sysDict = new SysDict();
            sysDict.setSort(index);
            sysDict.setStatus(1);
            sysDict.setValue(StringUtils.replaceStr(column, "\uFEFF", ""));
            sysDict.setName(StringUtils.replaceStr(column, "\uFEFF", ""));
            sysDict.setTypeCode(platformKey + type);
            sysDictList.add(sysDict);
            index++;
        }
        for (SysDict sysDict : sysDictList) {
            sysDictService.save(sysDict);
        }
        return Result.success();
    }
}
